<template>
  <div class="p-6">
    <el-row :gutter="12">
      <el-col :xs="24" :md="6" :lg="5">
        <el-card shadow="never" class="rounded-lg h-full">
          <template #header>
            <div class="font-600">{{ companyName }}</div>
          </template>
          <el-tree
            :data="deptTree"
            node-key="id"
            :props="{ label: 'name', children: 'children' }"
            highlight-current
            :expand-on-click-node="false"
            @node-click="onDeptClick"
          />
        </el-card>
      </el-col>

      <el-col :xs="24" :md="18" :lg="19">
        <el-card shadow="never" class="rounded-lg mb-3">
          <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="onSearch">
            <el-row :gutter="12" align="bottom">
              <el-col :xs="24" :md="5">
                <el-form-item label="手机号">
                  <el-input v-model="filters.mobile" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="5">
                <el-form-item label="姓名">
                  <el-input v-model="filters.name" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="5">
                <el-form-item label="性别">
                  <el-select v-model="filters.gender" placeholder="请选择" clearable>
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :md="4" class="flex justify-end items-end">
                <el-button type="primary" :loading="queryLoading" @click="onSearch">
                  <el-icon class="mr-1"><Search /></el-icon>
                  查询
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <el-card shadow="never" class="rounded-lg">
          <div v-loading="tableLoading">
            <el-table :data="tableData" border>
              <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
              <el-table-column label="姓名" prop="name" min-width="120" />
              <el-table-column label="手机号" prop="mobile" min-width="140" />
              <el-table-column label="部门" prop="deptName" min-width="140" />
              <el-table-column label="性别" prop="gender" width="90" align="center" />
              <el-table-column label="年龄" prop="age" width="90" align="center" />
              <el-table-column label="岗位" prop="position" min-width="140" />
              <el-table-column label="操作" width="100" align="center">
                <template #default="scope">
                  <el-link type="danger" @click="onDelete(scope.row)">删除</el-link>
                </template>
              </el-table-column>
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
            </el-table>
          </div>

          <div class="flex justify-end mt-4">
            <el-pagination
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="onSizeChange"
              @current-change="onPageChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

interface DeptNode {
  id: number;
  name: string;
  children?: DeptNode[];
}
interface PersonRow {
  id: number;
  name: string;
  mobile: string;
  deptId: number;
  deptName: string;
  gender: '男' | '女';
  age: number;
  position: string;
}

const companyName = '东营市海科瑞林化工有限公司';

const deptTree = ref<DeptNode[]>([]);
const allPersons = ref<PersonRow[]>([]);
const currentDeptId = ref<number | null>(null);

const filters = reactive({ mobile: '', name: '', gender: '' });
const queryLoading = ref(false);
const tableLoading = ref(false);

const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 });
const tableData = ref<PersonRow[]>([]);

const indexMethod = (i: number) => (pagination.currentPage - 1) * pagination.pageSize + i + 1;

const mockInit = () => {
  // 部门树（多层）
  const departments: DeptNode[] = [
    {
      id: 1,
      name: '生产部门',
      children: [
        { id: 11, name: '生产一班' },
        { id: 12, name: '生产二班' }
      ]
    },
    {
      id: 2,
      name: '设备部',
      children: [
        { id: 21, name: '设备维护组' },
        { id: 22, name: '设备管理组' }
      ]
    },
    {
      id: 3,
      name: '安环部',
      children: [
        { id: 31, name: '安全管理组' },
        { id: 32, name: '环保管理组' }
      ]
    },
    { id: 4, name: '工艺部' },
    { id: 5, name: '电仪部' }
  ];
  deptTree.value = departments;

  const names = [
    '王伟',
    '李娜',
    '张敏',
    '刘洋',
    '陈杰',
    '杨静',
    '黄磊',
    '周玲',
    '吴涛',
    '赵敏',
    '马强',
    '郑爽',
    '胡杨',
    '冯蕾',
    '罗超',
    '程辉',
    '石磊',
    '邓丽',
    '彭浩',
    '蔡霞'
  ];
  const positions = ['操作工', '维修工', '检维修工程师', '安全员', '工艺工程师', '电仪工程师', '班长', '主任'];

  const mobileOf = (idx: number) => `13${String(100000000 + idx).slice(0, 9)}`;

  const persons: PersonRow[] = [];
  let id = 1;
  const assign = (deptId: number, deptName: string, count: number) => {
    for (let i = 0; i < count; i++) {
      const name = names[(id + i) % names.length];
      const gender = (id + i) % 2 === 0 ? '男' : '女';
      const age = 24 + ((id + i) % 21);
      const position = positions[(id + i) % positions.length];
      persons.push({ id, name, mobile: mobileOf(id), deptId, deptName, gender, age, position });
      id++;
    }
  };

  // 分配人员到各部门
  assign(1, '生产部门', 8);
  assign(11, '生产一班', 6);
  assign(12, '生产二班', 6);
  assign(2, '设备部', 6);
  assign(21, '设备维护组', 6);
  assign(22, '设备管理组', 5);
  assign(3, '安环部', 5);
  assign(31, '安全管理组', 5);
  assign(32, '环保管理组', 4);
  assign(4, '工艺部', 6);
  assign(5, '电仪部', 6);

  allPersons.value = persons;
};

const onDeptClick = (node: DeptNode) => {
  currentDeptId.value = node.id;
  pagination.currentPage = 1;
  fetchList();
};

const formatDate = (d: any) => ''; // placeholder if needed later

const applyFilter = () => {
  const mobile = filters.mobile.trim();
  const name = filters.name.trim();
  const gender = filters.gender;
  return allPersons.value.filter((p) => {
    const inDept = currentDeptId.value ? p.deptId === currentDeptId.value || String(p.deptId).startsWith(String(currentDeptId.value)) : true;
    const m = mobile ? p.mobile.includes(mobile) : true;
    const n = name ? p.name.includes(name) : true;
    const g = gender ? p.gender === gender : true;
    return inDept && m && n && g;
  });
};

const refreshTable = (list: PersonRow[]) => {
  pagination.total = list.length;
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  tableData.value = list.slice(start, start + pagination.pageSize);
};

const fetchList = async (btn = true) => {
  if (btn) queryLoading.value = true;
  tableLoading.value = true;
  try {
    await new Promise((r) => setTimeout(r, 150));
    const filtered = applyFilter();
    refreshTable(filtered);
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchList();
};
const onSizeChange = (s: number) => {
  pagination.pageSize = s;
  pagination.currentPage = 1;
  fetchList(false);
};
const onPageChange = (p: number) => {
  pagination.currentPage = p;
  fetchList(false);
};

const onDelete = async (row: PersonRow) => {
  try {
    await ElMessageBox.confirm(`确认删除人员“${row.name}”？`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' });
    tableLoading.value = true;
    await new Promise((r) => setTimeout(r, 150));
    allPersons.value = allPersons.value.filter((x) => x.id !== row.id);
    if ((pagination.currentPage - 1) * pagination.pageSize >= allPersons.value.length && pagination.currentPage > 1) pagination.currentPage -= 1;
    await fetchList(false);
    ElMessage.success('删除成功');
  } catch (e: any) {
    if (e !== 'cancel' && e !== 'close') ElMessage.error('删除失败，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

onMounted(async () => {
  mockInit();
  await fetchList(false);
});
</script>
